/**
 * Copyright 2018 orivil.com. All rights reserved.
 * Use of this source code is governed by a MIT-style
 * license that can be found at https://mit-license.org.
 */

package session

import (
	"os"
	"time"
	"gitee.com/tugoer/orivil/config"
	"path/filepath"
)

var Env = func() *env {
	e, err := loadEnv()
	if err != nil {
		panic(err)
	}
	return e
}()

type env struct {
	// cookie key
	CookieKey  string `json:"cookie_key"`

	// 过期时间 /minute
	ExpireTime int64  `json:"expire_time"` // per minute

	// 每次更新时随机检查过期数量
	CheckExpireNumEachUpdate int    `json:"check_expire_num_each_update"`

	// 默认存储器的存储目录
	SessionDir               string `json:"session_dir"`
}

func (e *env) Expire() time.Duration {
	return time.Duration(e.ExpireTime)
}

func (e *env) File(sessionID string) string {
	return filename(e.SessionDir, sessionID)
}

func filename(dir, session string) string {
	return filepath.Join(dir, session)
}

func loadEnv() (e *env, err error) {
	dir := "./configs"
	err = os.MkdirAll(dir, os.ModePerm)
	if err != nil {
		return nil, err
	}
	e = &env{
		CookieKey:                "orivil-session",
		ExpireTime:               120, // 默认120分钟
		CheckExpireNumEachUpdate: 3,  // 建议设置在 2-3
		SessionDir:               "_sessions",
	}
	parser := config.NewJsonParser(dir)
	err = parser.ReadOrCreate("session", e)
	if err != nil {
		return nil, err
	}
	e.ExpireTime = e.ExpireTime * int64(time.Minute)
	return e, nil
}